<?php
// 应用公共文件

/**
 * 判断是否是移动端
 * @return false|true
 */
if (!function_exists('isMobile')) {
    function isMobile()
    {
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
            return true;
        }
        if (isset ($_SERVER['HTTP_VIA'])) {
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        if (isset ($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = ['nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg',
                'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu',
                'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave',
                'nexusone', 'cldc', 'midp', 'wap', 'mobile'];
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return true;
            }
        }
        if (isset ($_SERVER['HTTP_ACCEPT'])) {
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return true;
            }
        }
        return false;
    }
}

/**
 * 图片数组转json
 * @param $arr
 * @param $type 类型存入数据库类型
 * @return false|string
 */
if (!function_exists('imageToJson')) {
    function imageToJson($arr,$type='json'){
        foreach ($arr as $key => $item){
            if ($item==''){
                unset($arr[$key]);
            }
        }
        if ($type=='json'){
            return json_encode($arr);
        }else{
            return implode(',',$arr);
        }

    }
}

/**
 * 将数据库里面的配置转化为配置文件
 * @param string $group 配置分组
 * @return false|string
 */
if (!function_exists('dbToConfig')) {
    function dbToConfig($group=false){
        if (!$group){
            $groups = \think\facade\Db::name('config_group')->column('name');
        }else{
            $groups[] = $group;
        }

        foreach ($groups as $item){
            $config = \think\facade\Db::name('config')->where('group',$item)->where('state',1)->column('code,value');
            $config = array_column($config,'value','code');

            //value是json字符串 - 解析
            foreach ($config as $key=>$value){
                $data = json_decode($value, true);
                if (($data && is_object($data)) || (is_array($data) && !empty($data))) {
                    $config[$key] = $data;
                }
            }
            $file =config_path().$item.'.php';

            //获取配置写入
            $config = var_export($config, true);
            $config = str_replace('array (','[',$config);
            $config = str_replace(')',']',$config);
            $config = str_replace('\'true\'','true',$config);
            $config = str_replace('\'false\'','false',$config);
            file_put_contents($file, "<?php\t\r\t\r return " . $config . ";");
        }
    }
}

/**
 *  下载网络图片到本地服务器
 * @param string $url 请求地址
 * @return false|string
 */
if (!function_exists('downloadImageToLocal')) {
    function downloadImageToLocal($url = '',$type='goods',$path='./upload')
    {
        //图片存放路径
        $path = $path.'/'.$type.'/'.date('Ymd');
        if (!is_dir($path)){
            mkdir($path);
        }

        //图片扩展
        $ext=strrchr($url,'.');
        $save_to = $path.'/'.md5(time()).$ext;

        //存储下载到本地
        if (!preg_match('/(http:\/\/)|(https:\/\/)/i', $url)) {
            $url = 'http:'.$url;
        }
        $content = file_get_contents($url);
        file_put_contents($save_to, $content);
        $save_path = substr($save_to,1);
        //七牛上传
        if (Config::get('qiniu.open')) {
            \Qiniu::getInstance()->putFile(substr($save_path,1),  public_path().$save_path);
        }
        return  $save_path;
    }
}


/**
 * 生成二维码图片
 * @param string $url 请求地址
 * @return false|string
 */
if (!function_exists('Qrcode')) {
    function Qrcode($token, $url, $size = 8){ 
        $dir = date('Ymd'). '/';
        $patch = 'qrcode/' . $dir;
        if (!file_exists($patch)){
            mkdir($patch, 0755, true);
        }
        $file = 'qrcode/' .$dir . $token . '.png';
        $fileName =  $file;
        if (!file_exists($fileName)) {

            $level = 'L';
            $data = $url;
            QRcode::png($data, $fileName, $level, $size, 2, true);

            //七牛上传
            if (Config::get('qiniu.open')) {
                \Qiniu::getInstance()->putFile($file,  public_path().$file);
            }
        }
        return $file;
    }
}

/**
 * 数组字段获取
 * @param array $arr 原数组
 * @param string $filed 需要获取的字段
 * @return string
 */
if (!function_exists('array_filed')){
    function array_filed($arr, $filed){
        $filed = explode(",",$filed);
        foreach ($arr as $key=>$item){
            if (in_array($key,$filed)){
                continue;
            }
            unset($arr[$key]);
        }
        return $arr;
    }
}

/**
 * 反转url地址
 * @param array $parsed_url 需要反转parse_url方法
 * @return string
 * @author: An Yang
 * @since: 2019/7/24
 * @time: 11:41
 */
if (!function_exists('http_build_url')){
    function http_build_url(array $parsed_url) {
        $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
        $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
        $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
        $user     = isset($parsed_url['user']) ? $parsed_url['user'] : '';
        $pass     = isset($parsed_url['pass']) ? ':' . $parsed_url['pass']  : '';
        $pass     = ($user || $pass) ? "$pass@" : '';
        $path     = isset($parsed_url['path']) ? $parsed_url['path'] : '';
        $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
        $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
        return "$scheme$user$pass$host$port$path$query$fragment";
    }
}

/**
 * 图片完全路径
 * @param array $arr 原数组
 * @param string $filed 需要获取的字段
 * @return string
 */
if (!function_exists('image_absolute_path')){
    function image_absolute_path($path,$type='avatar'){
        return \think\facade\Config::get('site.'.$type).$path;
    }
}

/**
 * 是否拥有全权限
 * @param $arr
 * @return false|string
 */
if (!function_exists('checkAuth')) {
    function checkAuth($url){
        //拼接路由
        $module = app('http')->getName();
        $url = \think\helper\Str::lower($module.'/'.$url);
        //用户id
        $auth_uid = \think\facade\Config::get('login_admin.auth_uid');
        $auth_uid = session($auth_uid);
        return \auth\Auth::instance()->check($url, $auth_uid);
    }
}

/**
 * 权限标签的权限判定
 */
if (!function_exists('checkAuthLabel')) {
    function checkAuthLabel($Label){
        $auth_uid = \think\facade\Config::get('login_admin.auth_uid');
        $auth_uid = session($auth_uid);
        return \auth\Auth::instance()->check($Label, $auth_uid);
    }
}



/**
 *  request_ge请求
 * @param string $url 请求地址
 * @return false|string
 */
if (!function_exists('request_get')) {
    function request_get($url = '')
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 500);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}

/**
 * 返回配置参数
 * @param $name
 * @return array|mixed
 */
if (!function_exists('SysConfig')) {
    function SysConfig($name){
        $config = cache($name);
        if ($config){
            return $config;
        }
        $group = explode('.',$name);
        if (is_array($group)){
            $config =  \app\admin\model\Config::where('group',$group[0])->where('code',$group[1])->value('value');
        }else{
            $config = \app\admin\model\Config::where('group',$group)->field('code,value')->select()->toArray();
        }
        cache($name,$config);
        return $config;
    }
}

/**
 * 删除目录
 * @param $path
 * @return mixed
 */
if (!function_exists('deleteDir')) {
    function deleteDir($path){
        if (is_dir($path)) {
            //扫描一个目录内的所有目录和文件并返回数组
            $dirs = scandir($path);
            foreach ($dirs as $dir) {
                //排除目录中的当前目录(.)和上一级目录(..)
                if ($dir != '.' && $dir != '..') {
                    //如果是目录则递归子目录，继续操作
                    $sonDir = $path . '/' . $dir;
                    if (is_dir($sonDir)) {
                        //递归删除
                        deleteDir($sonDir);
                        //目录内的子目录和文件删除后删除空目录
                        @rmdir($sonDir);
                    } else {
                        //如果是文件直接删除
                        @unlink($sonDir);
                    }
                }
            }
            @rmdir($path);
        }
    }
}

/**
 * 系统日志
 */
if (!function_exists('admin_log')){
    function admin_log($admin_id = 0){
        if ($admin_id>0){
            $model = new  \app\admin\model\AdminLog();
            $model->params = request()->param()?:[];
            $model->method = app('http')->getName().'/'.request()->controller().'/'.request()->action();
            $model->request = request()->method();
            $model->admin_id = $admin_id;
            $model->save();
        }
    }
}




